package cc.realxyq.demo.aware;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;

/**
 *  为了日志对齐，故意设置的名字， 正常要 DemoAwarePostProcessor ，而且建议取名要尽量见名知意
 *  添加自定义的postprocessor 进行对bean的生命周期的影响
 * @author kwhan
 * @date 2022年01月12日 16:19
 */
@Slf4j
public class DemoAwareBeanPostProcessor implements DestructionAwareBeanPostProcessor {
    private static final String BEAN_NAME = "demoAware";
    public static final String LOG_FORMAT_MESSAGE = "步骤{}，DemoAwareProcessor.{} 方法执行了。。。 {}";

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (BEAN_NAME.equals(beanName)) {
            DemoAware demoAware = (DemoAware) bean;
            demoAware.getLongAdder().increment();
            log.warn(LOG_FORMAT_MESSAGE, demoAware.getLongAdder(), Thread.currentThread().getStackTrace()[1].getMethodName(), bean);
        }
        return DestructionAwareBeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (BEAN_NAME.equals(beanName)) {
            DemoAware demoAware = (DemoAware) bean;
            demoAware.getLongAdder().increment();
            log.warn(LOG_FORMAT_MESSAGE, demoAware.getLongAdder(), Thread.currentThread().getStackTrace()[1].getMethodName(), bean);
        }
        return DestructionAwareBeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    @Override
    public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
        if (BEAN_NAME.equals(beanName)) {
            DemoAware demoAware = (DemoAware) bean;
            demoAware.getLongAdder().increment();
            log.warn(LOG_FORMAT_MESSAGE, demoAware.getLongAdder(), Thread.currentThread().getStackTrace()[1].getMethodName(), bean);
        }
    }
}
